import { listen } from 'dom-helpers'
export default (designerRef, isPressSpace) => {
  let prevMoveXValue = [0, 0]
  let prevMoveYValue = [0, 0]
  // 拖拽处理
  const dragCanvas = (e: any) => {
    e.preventDefault()
    e.stopPropagation()

    if (e.which === 2) isPressSpace.value = true
    else if (!window.$KeyboardActive?.space) return

    // document.activeElement.blur()

    const startX = e.pageX
    const startY = e.pageY

    const listenMousemove = listen(window, 'mousemove', (e: any) => {
      const nx = e.pageX - startX
      const ny = e.pageY - startY

      const [prevMoveX1, prevMoveX2] = prevMoveXValue
      const [prevMoveY1, prevMoveY2] = prevMoveYValue

      prevMoveXValue = [prevMoveX2, nx]
      prevMoveYValue = [prevMoveY2, ny]

      designerRef.value.scrollLeft -= prevMoveX2 > prevMoveX1 ? Math.abs(prevMoveX2 - prevMoveX1) : -Math.abs(prevMoveX2 - prevMoveX1)
      designerRef.value.scrollTop -= prevMoveY2 > prevMoveY1 ? Math.abs(prevMoveY2 - prevMoveY1) : -Math.abs(prevMoveY2 - prevMoveY1)
    })

    const listenMouseup = listen(window, 'mouseup', () => {
      listenMousemove()
      listenMouseup()
      prevMoveXValue = [0, 0]
      prevMoveYValue = [0, 0]
      isPressSpace.value = false
    })
  }

  return {
    dragCanvas
  }
}
